import React from 'react';
import { Tag, Input, Tooltip, Icon } from 'antd';

export default class extends React.Component {
  state = {
    tags: (this.props.value || '').split(',').filter(x => x),
    inputVisible: false,
    inputValue: '',
  };

  handlePropsOnChange = () => {
    if (this.props.onChange) {
      this.props.onChange(this.state.tags.join(','));
    }
  }

  handleClose = (removedTag) => {
    const tags = this.state.tags.filter(tag => tag !== removedTag);

    this.setState({ tags }, this.handlePropsOnChange);
  }

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  }

  handleInputChange = (e) => {
    this.setState({ inputValue: e.target.value });
  }

  handleInputConfirm = () => {
    const state = this.state;
    const inputValue = state.inputValue;
    let tags = state.tags;
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue];
    }

    this.setState(
      {
        tags,
        inputVisible: false,
        inputValue: '',
      },
      this.handlePropsOnChange,
    );
  }

  saveInputRef = input => this.input = input

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.state.tags.join(',') && nextProps.value) {
      this.setState({
        tags: (nextProps.value || '').split(',').filter(x => x),
      })
    }
  }

  render() {
    const { tags, inputVisible, inputValue } = this.state;
    return (
      <div>
        {tags.map((tag, index) => {
          const isLongTag = tag.length > 20;
          const tagElem = (
            <Tag key={tag} closable={true} afterClose={() => this.handleClose(tag)}>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </Tag>
          );
          return isLongTag ? <Tooltip title={tag} key={tag}>{tagElem}</Tooltip> : tagElem;
        })}
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            size="small"
            style={{ width: 80 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && (
          <Tag
            onClick={this.showInput}
            style={{ background: '#fff', borderStyle: 'dashed' }}
          >
            <Icon type="plus" /> New Tag
          </Tag>
        )}
      </div>
    );
  }
}
